{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def sortedArrayToBST(self, nums: [int]) -> TreeNode:\n",
    "        length = len(nums)        \n",
    "        if length == 0:\n",
    "            return None\n",
    "        \n",
    "        mid = length//2\n",
    "        root = TreeNode(nums[mid])\n",
    "        \n",
    "        self.nums = nums\n",
    "        \n",
    "        def dfs(is_left: bool, left: int, right: int, father: TreeNode):\n",
    "            # null: empty subtree\n",
    "            if left > right:\n",
    "                return\n",
    "            mid = (left+right+1)//2\n",
    "            node = TreeNode(self.nums[mid])\n",
    "            if is_left:\n",
    "                father.left = node\n",
    "            else:\n",
    "                father.right = node\n",
    "            # if leaf node, return directly\n",
    "            if left == right:\n",
    "                return\n",
    "            # if non-leaf node, go deeper\n",
    "            dfs(True, left, mid-1, node)\n",
    "            dfs(False, mid+1, right, node)\n",
    "\n",
    "        dfs(True, 0, mid-1, root)\n",
    "        dfs(False, mid+1, length-1, root)\n",
    "\n",
    "        return root\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
